<route lang="json5" type="page">
  {
    needLogin: true,
    style: {
      navigationBarTitleText: '通知编辑',
      enablePullDownRefresh: true,
    },
  }
</route>

<script setup lang="ts">
import { ref } from 'vue'
import { onPullDownRefresh, onReachBottom } from '@dcloudio/uni-app'

// 搜索关键字
const searchKeyword = ref('')

// 收藏状态
const isFavorite = ref(false)

// 范围选择相关
const selectedRangeText = ref(null)
const selectedRange = ref([])
const showTreePicker = ref(false)

// 树形数据结构
const treeData = ref([
  {
    id: '1',
    name: 'A区',
    children: [
      {
        id: '1-1',
        name: '1号楼',
        children: [
          { id: '1-1-1', name: '1层' },
          { id: '1-1-2', name: '2层' },
          { id: '1-1-3', name: '3层' },
          { id: '1-1-4', name: '4层' },
          { id: '1-1-5', name: '5层' },
        ],
      },
      {
        id: '1-2',
        name: '2号楼',
        children: [
          { id: '1-2-1', name: '1层' },
          { id: '1-2-2', name: '2层' },
          { id: '1-2-3', name: '3层' },
        ],
      },
    ],
  },
  {
    id: '2',
    name: 'B区',
    children: [
      {
        id: '2-1',
        name: '5号楼',
        children: [
          { id: '2-1-1', name: '1层' },
          { id: '2-1-2', name: '2层' },
        ],
      },
    ],
  },
])

// 消息编辑内容
const messageContent = ref('')

// 消息历史记录
const messageHistory = ref<string[]>([])
const showHistory = ref(false)

// 加载状态
const loading = ref(false)

// ba-tree-picker 组件引用
const treePickerRef = ref()

// 处理搜索
function handleSearch() {
  if (!searchKeyword.value.trim()) {
    uni.showToast({
      title: '请输入搜索关键字',
      icon: 'none',
    })
    return
  }

  uni.showToast({
    title: `搜索: ${searchKeyword.value}`,
    icon: 'none',
  })
}

// 取消搜索
function cancelSearch() {
  searchKeyword.value = ''
}

// 切换收藏状态
function toggleFavorite() {
  isFavorite.value = !isFavorite.value
  uni.showToast({
    title: isFavorite.value ? '已收藏' : '取消收藏',
    icon: 'success',
  })
}

// 显示范围选择器
function showRangeSelector() {
  treePickerRef.value?._show()
}

// 范围选择确认
function onRangeSelect(selectedIds: string[], selectedNames: string, allSelectedList: any[]) {
  console.log(selectedIds, selectedNames, allSelectedList)
  selectedRange.value = selectedIds
  selectedRangeText.value = selectedNames
}

// 发送消息
function sendMessage() {
  if (!messageContent.value.trim()) {
    uni.showToast({
      title: '请输入消息内容',
      icon: 'none',
    })
    return
  }

  loading.value = true

  setTimeout(() => {
    loading.value = false

    // 保存到历史记录
    messageHistory.value.unshift(`${new Date().toLocaleString()}: ${messageContent.value}`)
    if (messageHistory.value.length > 50) {
      messageHistory.value = messageHistory.value.slice(0, 50)
    }

    uni.showToast({
      title: '发送成功',
      icon: 'success',
    })

    messageContent.value = ''
  }, 1000)
}

// 清屏
function clearContent() {
  if (!messageContent.value.trim()) {
    uni.showToast({
      title: '编辑框已经是空的',
      icon: 'none',
    })
    return
  }

  uni.showModal({
    title: '提示',
    content: '确定要清空编辑内容吗？',
    success: (res) => {
      if (res.confirm) {
        messageContent.value = ''
        uni.showToast({
          title: '已清空',
          icon: 'success',
        })
      }
    },
  })
}

// 显示消息历史
function showMessageHistory() {
  uni.navigateTo({
    url: '/pages-admin/admin/message/history',
  })
}

// 关闭历史记录弹窗
function closeHistory() {
  showHistory.value = false
}

// 从历史记录中选择消息
function selectHistoryMessage(message: string) {
  const content = message.split(': ').slice(1).join(': ')
  messageContent.value = content
  showHistory.value = false
  uni.showToast({
    title: '已填入编辑框',
    icon: 'success',
  })
}

// 下拉刷新
onPullDownRefresh(async () => {
  setTimeout(() => {
    uni.stopPullDownRefresh()
    uni.showToast({
      title: '刷新完成',
      icon: 'success',
    })
  }, 1000)
})

// 上拉加载更多
onReachBottom(() => {
  console.log('上拉加载更多')
})
</script>

<template>
  <view class="message-edit-page min-h-screen bg-gray-50">
    <view class="content-section px-4 py-3">
      <!-- 范围选择区域 -->
      <view class="range-section mb-4" @click="showRangeSelector">
        <wd-cell title="选择范围" :value="selectedRangeText || '请选择'" />
      </view>

      <!-- 消息编辑区域 -->
      <view class="editor-section">
        <view class="editor-header mb-3">
          <text class="text-base text-gray-800 font-medium">
            通知消息编辑
          </text>
        </view>

        <view class="editor-content overflow-hidden rounded-lg bg-white">
          <wd-textarea
            v-model="messageContent" placeholder="请输入通知消息内容..." :maxlength="500" clearable show-word-limit
            class="message-textarea"
          />
        </view>
      </view>
    </view>

    <!-- 底部操作按钮 - 固定在底部 -->
    <view class="action-buttons-fixed pb-safe">
      <view class="action-buttons flex justify-center gap-4 border-t border-gray-200 bg-white px-4 py-3">
        <wd-button type="warning" size="small" plain custom-class="flex-1" @click="clearContent">
          清屏
        </wd-button>
        <wd-button type="info" size="small" plain custom-class="flex-1" @click="showMessageHistory">
          消息历史
        </wd-button>
        <wd-button type="primary" size="small" :loading="loading" custom-class="flex-1" @click="sendMessage">
          发送
        </wd-button>
      </view>
    </view>

    <!-- 范围选择器 -->
    <ba-tree-picker
      ref="treePickerRef" :localdata="treeData" :selected-data="selectedRange" title="选择范围"
      :multiple="true" @select-change="onRangeSelect"
    />
  </view>
</template>

<style scoped lang="scss">
.message-edit-page {
  padding-bottom: 120rpx;
  /* 为底部固定按钮留出空间 */
}

.content-section {
  min-height: calc(100vh - 240rpx);
}

.range-selector {
  cursor: pointer;
  transition: all 0.2s;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
}

.range-selector:active {
  background-color: #f8fafc;
}

.message-textarea {
  width: 100%;
}

:deep(.message-textarea .wd-textarea__inner) {
  padding: 24rpx;
  background-color: #fafafa;
  font-size: 32rpx;
  line-height: 1.5;
}

.action-buttons-fixed {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  z-index: 100;
  background: white;
  border-top: 1rpx solid #e5e5e5;
}

:deep(.action-buttons .wd-button) {
  flex: 1;
  margin: 0 8rpx;
}

.history-popup {
  height: 100%;
  display: flex;
  flex-direction: column;
  background: white;
}

.history-list {
  max-height: calc(70vh - 120rpx);
}

.history-item {
  word-break: break-all;
  cursor: pointer;
  transition: background-color 0.2s;
}

.history-item:active {
  background-color: #e5e7eb;
}

.empty-state {
  color: #9ca3af;
}

:deep(.wd-search) {
  .wd-search__input {
    font-size: 28rpx;
  }
}

/* 修复按钮样式 */
:deep(.wd-button) {
  white-space: nowrap;
}

:deep(.wd-button--large) {
  height: 80rpx;
  font-size: 32rpx;
}
</style>
